package dataView

import (
	"context"
	"encoding/json"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/code"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/common"
	"gitee.com/liuxuezhan/ar-platform/base-common/auth"
	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/client/dataview"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/rpc"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type InsertDataViewLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 新增或修改
func NewInsertDataViewLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InsertDataViewLogic {
	return &InsertDataViewLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InsertDataViewLogic) InsertDataView(req *types.InsertDataViewReq) (resp *types.Empty, err error) {
	userId := auth.GetTokenUid(l.ctx)
	if userId == 0 {
		return nil, code.NotLogin
	}

	if _, ok := common.All[req.ModelType]; !ok {
		return nil, code.ParamsInvalid
	}

	if _, ok := common.All[req.ModelType][req.Type]; !ok {
		return nil, code.ParamsInvalid
	}

	value := map[string]interface{}{}

	if _, ok := common.Numerical[req.Type]; ok {
		value["numerical"] = req.Value.Numerical
	}

	if _, ok := common.Status[req.Type]; ok {
		value["status"] = req.Value.Status
	}

	if _, ok := common.Ratio[req.Type]; ok {
		value["top_up"] = req.Value.TopUp
		value["withdraw"] = req.Value.Withdraw
	}

	if _, ok := common.Bank[req.Type]; ok {
		value["bank_num"] = req.Value.BankNum
		value["usdt_num"] = req.Value.UsdtNum
		value["wallet"] = req.Value.Wallet
		value["new_up"] = req.Value.NewUp
		value["upi"] = req.Value.Upi
	}

	if _, ok := common.Char[req.Type]; ok {
		value["char"] = req.Value.Char
	}

	if _, ok := common.Bidding[req.Type]; ok {
		value["binding_option"] = req.Value.BindingOption
		value["binding_condition"] = req.Value.BindingCondition
	}

	va, _ := json.Marshal(value)

	u, err := l.svcCtx.SettingService.DataView.InsertDataView(l.ctx, &dataview.InsertDataViewReq{
		MerchantId: 1,                            // 商户ID
		ModelType:  rpc.ModelType(req.ModelType), // 模块类型,1:用户资产,2:用户基础,3:运营,9:其他
		Type:       req.Type,                     // 具体类型
		Value:      string(va),                   // 值
		Operator:   "",                           // 操作人
		OperatorId: userId,                       // 操作人ID
		Ip:         headInfo.GetClientIp(l.ctx),
		IpAddress:  "",
	})

	if err != nil {
		logc.Error(l.ctx, "InsertDataView err:", err)
		return nil, err
	}

	if u.Code != int64(code.SettingRpcSuccessful.Code()) {
		return nil, code.BusinessFailure
	}

	resp = &types.Empty{}
	return
}
